package czt.ocr.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import czt.ocr.entity.BaseVoltage;
import czt.ocr.entity.ControlArea;
import czt.ocr.entity.EFile;
import czt.ocr.entity.Substation;
import czt.ocr.mapper.BaseVoltageMapper;
import czt.ocr.mapper.ControlAreaMapper;
import czt.ocr.mapper.EFileMapper;
import czt.ocr.mapper.SubstationMapper;
import czt.ocr.service.EFileService;
import czt.ocr.util.TagFileParser;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author czt
 * @version 1.0
 * @since 2025/4/6
 */
@Service
public class EFileServiceImpl implements EFileService {

    @Autowired
    private EFileMapper eFileMapper;

    @Autowired
    private BaseVoltageMapper baseVoltageMapper;

    @Autowired
    private ControlAreaMapper controlAreaMapper;

    @Autowired
    private SubstationMapper substationMapper;


    @Override
    public void load() {
        String fileName = "/Users/project/study/Ocr/src/main/resources/eFile.xlsx";

        // 检查并创建目录
        File file = new File(fileName).getParentFile();
        if (!file.exists()) {
            file.mkdirs();
        }
        List<EFile> eFiles = eFileMapper.getEFiles();

        EasyExcel.write(fileName,EFile.class).sheet("信息").doWrite(eFiles);
        // System.out.println("eFiles = " + eFiles);

    }

    @Override
    public void save() {
        List<EFile> eFiles = new ArrayList<>();
        String path = "/Users/project/study/Ocr/src/main/resources/e.xlsx";
        EasyExcel.read(path,EFile.class,new AnalysisEventListener<EFile>(){


            @Override
            public void invoke(EFile eFile, AnalysisContext analysisContext) {
                eFiles.add(eFile);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {

            }
        }).sheet("Sheet1").doRead();
        for (EFile eFile : eFiles) {
            eFileMapper.insertEFile(eFile);
        }
    }

    @Override
    public void save2() throws IOException {
        String filePath = "data/test.CIME";
        Map<String, TagFileParser.TableData> data = TagFileParser.parseFile(filePath);

        // 处理BaseVoltage数据
        if (data.containsKey("BaseVoltage")) {
            TagFileParser.TableData tableData = data.get("BaseVoltage");
            List<BaseVoltage> baseVoltages = convertToBaseVoltage(tableData);
            if (!baseVoltages.isEmpty()) {
                for (BaseVoltage baseVoltage : baseVoltages) {
                    baseVoltageMapper.insertBaseVoltage(baseVoltage);
                }
            }
        }

        // 处理ControlArea数据
        if (data.containsKey("ControlArea::kedong")) {
            TagFileParser.TableData tableData = data.get("ControlArea::kedong");
            List<ControlArea> controlAreas = convertToControlArea(tableData);
            if (!controlAreas.isEmpty()) {
                for (ControlArea controlArea : controlAreas) {
                    controlAreaMapper.insertControlArea(controlArea);
                }
            }
        }

        // 处理Substation数据
        if (data.containsKey("Substation::kedong")) {
            TagFileParser.TableData tableData = data.get("Substation::kedong");
            List<Substation> substations = convertToSubstation(tableData);
            if (!substations.isEmpty()) {
                for (Substation substation : substations) {
                    substationMapper.insertSubstation(substation);
                }
            }
        }
    }

    @Override
    public void load2() {
        String filePath = "/Users/project/study/Ocr/src/main/resources/data/load.CIME";
        try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(filePath),
                StandardCharsets.UTF_8)) {

            // 1. 导出BaseVoltage数据
            exportBaseVoltageData(writer);

            // 2. 导出ControlArea数据
            exportControlAreaData(writer);

            // 3. 导出Substation数据
            exportSubstationData(writer);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private List<BaseVoltage> convertToBaseVoltage(TagFileParser.TableData tableData) {
        List<BaseVoltage> result = new ArrayList<>();
        List<String> fields = tableData.getFields();

        for (List<String> row : tableData.getRows()) {
            BaseVoltage item = new BaseVoltage();
            for (int i = 0; i < fields.size(); i++) {
                String field = fields.get(i);
                String value = i < row.size() ? row.get(i) : null;

                switch (field) {
                    case "Num":
                        item.setNum(value != null ? Integer.parseInt(value) : null);
                        break;
                    case "mRID":
                        item.setMrid(value);
                        break;
                    case "name":
                        item.setName(value);
                        break;
                    case "nomkV":
                        item.setNomkV(value != null ? Double.parseDouble(value) : null);
                        break;
                }
            }
            result.add(item);
        }
        return result;
    }

    private List<ControlArea> convertToControlArea(TagFileParser.TableData tableData) {
        List<ControlArea> result = new ArrayList<>();
        List<String> fields = tableData.getFields();

        for (List<String> row : tableData.getRows()) {
            ControlArea item = new ControlArea();
            for (int i = 0; i < fields.size(); i++) {
                String field = fields.get(i);
                String value = i < row.size() ? row.get(i) : null;

                switch (field) {
                    case "Num":
                        item.setNum(value != null ? Integer.parseInt(value) : null);
                        break;
                    case "mRID":
                        item.setMrid(value);
                        break;
                    case "name":
                        item.setName(value);
                        break;
                    case "Parent":
                        item.setParent(value);
                        break;
                }
            }
            result.add(item);
        }
        return result;
    }

    private List<Substation> convertToSubstation(TagFileParser.TableData tableData) {
        List<Substation> result = new ArrayList<>();
        List<String> fields = tableData.getFields();

        for (List<String> row : tableData.getRows()) {
            Substation item = new Substation();
            for (int i = 0; i < fields.size(); i++) {
                String field = fields.get(i);
                String value = i < row.size() ? row.get(i) : null;

                switch (field) {
                    case "Num":
                        item.setNum(value != null ? Integer.parseInt(value) : null);
                        break;
                    case "mRID":
                        item.setMrid(value);
                        break;
                    case "name":
                        item.setName(value);
                        break;
                    case "ControlArea":
                        item.setControlArea(value);
                        break;
                }
            }
            result.add(item);
        }
        return result;
    }

    private void exportBaseVoltageData(BufferedWriter writer) throws IOException {
        List<BaseVoltage> data = baseVoltageMapper.getBaseVoltages();

        writer.write("<BaseVoltage>");
        writer.newLine();
        writer.write("@\tNum\tmRID\tname\tnomkV");
        writer.newLine();

        for (BaseVoltage item : data) {
            writer.write(String.format("#\t%d\t%s\t%s\t%.2f",
                    item.getNum(),
                    item.getMrid(),
                    item.getName(),
                    item.getNomkV()));
            writer.newLine();
        }

        writer.write("</BaseVoltage>");
        writer.newLine();
    }

    private void exportControlAreaData(BufferedWriter writer) throws IOException {
        List<ControlArea> data = controlAreaMapper.getControlAreas();

        writer.write("<ControlArea::kedong>");
        writer.newLine();
        writer.write("@\tNum\tmRID\tname\tParent");
        writer.newLine();

        for (ControlArea item : data) {
            writer.write(String.format("#\t%d\t%s\t%s\t%s",
                    item.getNum(),
                    item.getMrid(),
                    item.getName(),
                    item.getParent()));
            writer.newLine();
        }

        writer.write("</ControlArea::kedong>");
        writer.newLine();
    }

    private void exportSubstationData(BufferedWriter writer) throws IOException {
        List<Substation> data = substationMapper.getSubstations();

        writer.write("<Substation::kedong>");
        writer.newLine();
        writer.write("@\tNum\tmRID\tname\tControlArea");
        writer.newLine();

        for (Substation item : data) {
            writer.write(String.format("#\t%d\t%s\t%s\t%s",
                    item.getNum(),
                    item.getMrid(),
                    item.getName(),
                    item.getControlArea()));
            writer.newLine();
        }

        writer.write("</Substation::kedong>");
        writer.newLine();
    }
}
